//
//  STTabBar.swift
//  STVVeibo
//
//  Created by leergou on 16/7/19.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

import UIKit

class STTabBar: UITabBar {

    // 定义闭包属性,点击事件外传
    var closure: (()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
         setupUI()
    }
    
    //MARK: - buttonClick
    @objc private func buttonClick(){
        
        closure?()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - setupUI
    private func setupUI() {
//        backgroundColor = RGB(237, green: 237, blue: 237)
        addSubview(composeButton)
    }
    
    //MARK: - layoutSubviews
    override func layoutSubviews() {
        // 不调用父类方法, items 前后层次有问题,导致 tabar 的主题颜色成了透明
        super.layoutSubviews()
        // 计算 UITabBarButton 的宽度
        let width = frame.width * 0.2
        var index: CGFloat = 0
        
        for item in subviews {
            
            if  item.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                // 设置 UITabBarButton 的 frame
                item.frame.origin.x = index * width
                // 忘记了给宽度赋值,导致了 items 按4 个计算
                item.frame.size.width = width
                
                index++
                
                if index == 2 {

                    index++
                }
            }
        }
        composeButton.center.x = frame.width * 0.5
    }
    
    //MARK: - lazy
    lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        // 添加监听
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
       button.sizeToFit()
        return button
    }()
}










